//
//  SISSLoginManger.m
//  SISSAPP
//
//  Created by 袁应荣 on 2019/6/26.
//  Copyright © 2019 优房网. All rights reserved.
//

#import "SISSLoginManger.h"
#import "SISSUserAccount.h"
#import <SAMKeychain/SAMKeychain.h>
#import "SISSTabBarController.h"
#import <Hyphenate/Hyphenate.h>

#import "SISSNetworkingManager+Message.h"
#import "SISSJsonRequestNetworkingManager+Login.h"

@interface SISSLoginManger ()<EMClientDelegate>

@end
@implementation SISSLoginManger

+ (instancetype)shareInstance {
    static SISSLoginManger *instance;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[SISSLoginManger alloc] init];
    });
    
    return instance;
}

- (void)autoLoginDidCompleteWithError:(EMError *)aError {
    if (aError) {
//        [self loginIMAccount];
    }
}

- (void)loginWithUserName:(NSString *)userName password:(NSString *)password {
    
    [SISSUserAccount shared].access_token = nil;
    [SISSUserAccount shared].token_type = nil;
    NSDictionary *parameters = @{@"username": userName,
                                 @"password": password};
    [SISSPublicSingleton shared].isHud = NO;//
    [kJsonRequestNetworkingManager loginWithParameters:parameters successBlock:^(id  _Nonnull responseObject) {
        
        NSLog(@"%@",responseObject);
        
        if ([responseObject[@"code"] integerValue] == 200) {
            // 登录成功
            NSDictionary *dict = responseObject[@"data"];
            NSMutableDictionary *saveDict = [NSMutableDictionary dictionaryWithDictionary:dict];
            [saveDict setValue:userName forKey:@"userName"];
            [[SISSUserAccount shared] saveUserAcountInfoWithDict:saveDict];
            
            [kJsonRequestNetworkingManager requestLoginPersonInfoWithName:userName successBlock:^(id  _Nonnull responseObject) {
                if ([responseObject[@"code"] integerValue] == 200) {
                    
                    NSDictionary *pDict = responseObject[@"data"];
                    if (![PublicUtil isBlankDictionary:pDict]) {
                        NSMutableDictionary *saveDict = [NSMutableDictionary dictionaryWithDictionary:dict];
                        [saveDict setValue:userName forKey:@"userName"];
                        [saveDict addEntriesFromDictionary:pDict];
                        
                        [[SISSUserAccount shared] saveUserAcountInfoWithDict:saveDict];
                        // 存储用户/更新当前账号
                        [SISSUserDefaultsTool saveObject:userName forKey:CURRENTID];
                        // 存储用户登录状态
                        [SISSUserDefaultsTool saveObject:userName forKey:CURRENTLOGIN];
                        // 保存用户密码到钥匙串
                        [SAMKeychain setPassword:password forService:BUNDLE_ID account:userName];
                        BOOL isAutoLogin = [EMClient sharedClient].options.isAutoLogin;
                        [[EMClient sharedClient] addDelegate:self delegateQueue:nil];
                        if (!isAutoLogin) {
                            [self loginIMAccount];
                        } else {
                            [self login];
                        }
                        
                    } else {
                        [[UIApplication sharedApplication].keyWindow.rootViewController alertWithMessage:@"您目前为无星级，暂不可登录。"];
                    }
                    
                } else {
                    
                    NSString *dataStr = responseObject[@"message"];
                    
                    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                        [[UIApplication sharedApplication].keyWindow.rootViewController alertWithMessage:dataStr];
                    }];
                }
                
            } failed:^(NSError * _Nonnull error) {
                NSLog(@"%@",error);
                
            }];
            
        } else {
            
            NSString *dataStr = responseObject[@"message"];
            
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                [[UIApplication sharedApplication].keyWindow.rootViewController alertWithMessage:dataStr];
                return;
            }];
        }
        
    } failed:^(NSError * _Nonnull error) {
        [[UIApplication sharedApplication].keyWindow.rootViewController alertWithMessage:@"连接服务器失败，请重新登录"];
        NSLog(@"%@",error);
    }];
}

- (void)loginIMAccount {
    
    [SISSPublicSingleton shared].isHud = YES;
    [MBProgressHUD YYR_ShowHUD:YES];
    [kNetworkManager requestIMAccountWithSuccess:^(NSDictionary *userData) {
        
        NSLog(@"userData %@",userData);
        if (![PublicUtil isBlankDictionary:userData]) {
            [SISSUserAccount shared].imAccount = userData[@"username"];
            [self loginIMChatWithUserData:userData];
        } else {
            [[UIApplication sharedApplication].keyWindow.rootViewController alertWithMessage:@"获取环信账号为空"];
        }
        
        
    } failed:^(NSError *error) {
        [[UIApplication sharedApplication].keyWindow.rootViewController alertWithMessage:@"连接服务器失败，请重新登录"];
        NSLog(@"%@",error);
    }];
}

#pragma mark - 登录环信
- (void)loginIMChatWithUserData:(NSDictionary *)userData {
    
    
    [[EMClient sharedClient] loginWithUsername:userData[@"username"]
                                      password:userData[@"password"]
                                    completion:^(NSString *aUsername, EMError *aError) {
                                        if (!aError) {
                                            //                                                [[EMClient sharedClient].options setIsAutoLogin:YES];
                                            EMPushOptions *pushOptions = [[EMClient sharedClient] pushOptions];
                                            pushOptions.displayStyle = EMPushDisplayStyleMessageSummary; // 显示消息内容
                                            //    pushOptions.displayStyle = EMPushDisplayStyleSimpleBanner; // 显示“您有一条新消息”
                                            [pushOptions setNoDisturbStatus:EMPushNoDisturbStatusClose];
                                            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                                                [[EMClient sharedClient] updatePushOptionsToServer];
                                            });
                                            
                                            [[EMClient sharedClient].options setIsAutoLogin:YES];
                                            [self login];
                                            NSLog(@"环信登陆成功");
                                        } else {
                                            NSLog(@"环信登陆失败");
                                            [[UIApplication sharedApplication].keyWindow.rootViewController alertWithMessage:@"连接服务器失败，请重新登录(环信登陆失败)"];
                                            //                                            [self loginIMChatWithUserData:userData];
                                        }
                                    }];
}


/**
 登录
 */
- (void)login {
    
    //    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    //        // 动画
    //            CATransition *animation = [[CATransition alloc] init];
    //            animation.duration = 1.0;
    //            animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    //            animation.type = kCATransitionReveal;
    
    SISSTabBarController *tabBarController = [[SISSTabBarController alloc] init];
    //    tabBarController.selectedIndex = 3;
    // 更换控制器
    [UIApplication sharedApplication].keyWindow.rootViewController = tabBarController;
    //            [[UIApplication sharedApplication].keyWindow.layer addAnimation:animation forKey:@"animation"];
    //    });
}


@end
